import React, { useState } from "react";
import { Button, Card, Form, Input, InputNumber, message, Select } from "antd";
import { useNavigate } from "react-router-dom";
import { ArrowLeftOutlined } from "@ant-design/icons";
import axios from "axios";
import { useEffect } from "react";
import PictureWall from "./picture_wall";
import RichTextEditor from "./rich_text_editor";
import { connect } from "react-redux";

const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 4,
    },
    md: {
      span: 4,
    },
    lg: {
      span: 4,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
    md: {
      span: 8,
    },
    lg: {
      span: 8,
    },
  },
};

const editorFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    md: {
      span: 16,
    },
    lg: {
      span: 16,
    },
  },
};

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 4,
    },
  },
};

function Add(props) {
  const navigate = useNavigate();
  let [cateList, setCateList] = useState([]);
  const { userInfo } = props;

  const [form] = Form.useForm();

  const reqCateList = async () => {
    const responce = await axios.get(
      "http://api.shop.eduwork.cn/api/admin/category",

      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );

    // 因为添加分类时，只能用二级分类，一级分类无效，因此需遍历出所有二级分类id
    // 不能直接返回所有ID， 应该返回对象数组，这样用户才能选择名字，传给服务器id
    const resultArray = responce.data.map((item) => {
      return item.children;
    });

    const newCateList = resultArray.reduce((pre, cur) => {
      return [...pre, ...cur];
    });

    setCateList(newCateList);
  };

  const addProduct = async (values) => {
    const responce = await axios.post(
      "http://api.shop.eduwork.cn/api/admin/goods",
      values,

      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );

    if (responce.status === 201) {
      message.success("商品添加成功");
      navigate("/admin/product");
    } else {
      message.error(responce.message);
    }
  };

  const setDetails = (content) => {
    form.setFieldsValue({ details: content });
  };

  const onFinish = (values) => {
    values.cover = values.cover[0].key;
    addProduct(values);
  };

  const suffixSelector = (
    <Form.Item name="suffix" noStyle>
      <Select
        style={{
          width: 70,
        }}
      >
        <Option value="USD">$</Option>
        <Option value="CNY">¥</Option>
      </Select>
    </Form.Item>
  );

  useEffect(() => {
    reqCateList();
    // eslint-disable-next-line
  }, []);

  return (
    <div>
      <Card
        title={
          <div className="detail-top">
            <Button
              type="link"
              onClick={() => {
                navigate(-1);
              }}
            >
              <ArrowLeftOutlined style={{ fontSize: "20px" }} />
            </Button>
            <span> 添加商品</span>
          </div>
        }
      >
        <Form
          {...formItemLayout}
          form={form}
          name="register"
          onFinish={onFinish}
          initialValues={{
            residence: ["zhejiang", "hangzhou", "xihu"],
            prefix: "86",
          }}
          scrollToFirstError
        >
          <Form.Item
            name="title"
            label="商品名称"
            rules={[
              {
                required: true,
                message: "Please input product title!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="description"
            label="商品描述"
            rules={[
              {
                required: true,
                message: "Please input product description!",
                //whitespace: true,
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="category_id"
            label="商品类别"
            rules={[
              {
                required: true,
                message: "Please select category_id!",
              },
            ]}
          >
            <Select placeholder="select category_id">
              {cateList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="price"
            label="商品价格"
            rules={[
              {
                required: true,
                message: "Please input product price!",
              },
            ]}
          >
            <InputNumber
              addonAfter={suffixSelector}
              style={{
                width: "100%",
              }}
            />
          </Form.Item>

          <Form.Item
            name="stock"
            label="商品库存"
            rules={[
              {
                required: true,
                message: "Please input product stock!",
              },
            ]}
          >
            <InputNumber
              style={{
                width: "100%",
              }}
            />
          </Form.Item>

          <Form.Item
            name="cover"
            label="商品图片"
            rules={[
              {
                required: true,
                message: "Please input product pic!",
              },
            ]}
          >
            <PictureWall></PictureWall>
          </Form.Item>

          <Form.Item
            {...editorFormItemLayout}
            name="details"
            label="商品详情"
            rules={[
              {
                required: true,
                message: "Please input product detail",
              },
            ]}
          >
            <RichTextEditor setDetails={setDetails} />
          </Form.Item>

          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}

export default connect((state) => ({ userInfo: state.userInfo }))(Add);
